package com.google.code.gestion_de_conferences;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
 * This Activity creates all reservations 
 * 
 * @author Rayan Zahab <differentruna@gmail.com> 
 */
public class ReservationActivity extends Activity {

        private TextView tvDisplayDate;
        private Button btnChangeDate, btnReserve;
        AABDatabaseManager db;
        private int year;
        private int month;
        private int day;
        private String selectedUser;
        private Date selectedDate;
        public int roomId ;
        private MyData[] values ;
        private final DateFormat ourFormat = new SimpleDateFormat("MM/dd/yyyy");
        TextView reg_room_name,  reg_room_address ,reg_room_description ,reg_room_capacity;
        
        static final int DATE_DIALOG_ID = 999;
        /**
         * Initiates the activity
         * @author Rayan Zahab <differentruna@gmail.com> 
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.reservation);
            db = new AABDatabaseManager(this);
            //Set date to current Day
            setCurrentDateOnView();
            //Add Buttons listeners
            addListenerOnButton();
             //Populate spinners values
            addItemsOnSpinners();
         
            reg_room_name = (TextView) findViewById(R.id.reg_room_name);
            reg_room_address = (TextView) findViewById(R.id.reg_room_address);
            reg_room_capacity = (TextView) findViewById(R.id.reg_room_capacity);
            reg_room_description = (TextView) findViewById(R.id.reg_room_description);
                    
             //Get the id of the room we selected
            Intent roomsListIntent = getIntent();           
            roomId = roomsListIntent.getIntExtra("selectedRoomPosition", -1);
            //If we got here with no room selected go back to roomList page
            if (roomId == -1)
            {
                Toast.makeText(this, "No room selected for reservation", Toast.LENGTH_LONG).show();
                Intent i = new Intent(getApplicationContext(), RoomsListActivity.class);
                startActivity(i);
            }
            String name = db.getValueByParam(0,1,"Room",roomId+"");
            String address = db.getValueByParam(0,2,"Room",roomId+"");
            String capacity = db.getValueByParam(0,3,"Room",roomId+"");
            String description = db.getValueByParam(0,4,"Room",roomId+"");
            //Get room's info
            reg_room_name.setText(Html.fromHtml("<b>"+getString(R.string.room_namei)+"</b>")+" : "+name); 
            reg_room_address.setText(Html.fromHtml("<b>"+getString(R.string.addressi)+"</b>")+" : "+address); 
            reg_room_capacity.setText(Html.fromHtml("<b>"+getString(R.string.capacityi)+"</b>")+" : "+capacity); 
            reg_room_description.setText(Html.fromHtml("<b>"+getString(R.string.description)+"</b>")+" : "+description);                                        
       
        }
        /** Populate values to Spinners:from , to , users
         * @author Rayan Zahab <differentruna@gmail.com> 
         */
        public void addItemsOnSpinners() {
                 
            Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
            Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
            Spinner users_spinner = (Spinner) findViewById(R.id.users_spinner);
            
            List<String> from ,to;
            from = new ArrayList<String>();
            to = new ArrayList<String>();
            for(int position=8;position<23;position++)
            {
                from.add(""+position);
                to.add(""+position);
            }
            //Get all users from the db
            ArrayList<ArrayList<Object>> allUsersArrays = new ArrayList<ArrayList<Object>>();                   
            User user = new User();
            allUsersArrays = db.getTablesRowsAsArrays (user);
            
            //array that will hold user data to be displayed
            values = new MyData[allUsersArrays.size()];

            String val="";

            int user_count=0;
            //check if we only have the admin then we have no users to display                                                                          
            if(allUsersArrays.size()<=1)
            {
                values = new MyData[1];
                values[0] = new MyData("No items to display","0");
                Toast.makeText(this, "No Users to create reservation for!", Toast.LENGTH_LONG).show();
                Intent i = new Intent(getApplicationContext(), UsersListActivity.class);
                startActivity(i);
                    
            }
            else if( allUsersArrays.size()>1)
            {
                values = new MyData[allUsersArrays.size()-1];
                //array that will hold user data to be displayed
                for (int position=0; position < allUsersArrays.size(); position++)
                {
                    ArrayList<Object> row = allUsersArrays.get(position);                           
                    //check the is_admin value
                    if(!(row.get(6)).equals("1") )
                    {
                            val = row.get(1).toString()+"-"+row.get(3).toString();
                            values[user_count] = new MyData( val,row.get(0).toString());     
                            user_count=user_count+1;
                    }                                                               
                } 
             }
                            
            ArrayAdapter<MyData> usersAdapter = new ArrayAdapter<MyData>(this,
                                                                                             android.R.layout.simple_spinner_item, values);
            usersAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            users_spinner.setAdapter(usersAdapter);
            
            ArrayAdapter<String> fromAdapter = new ArrayAdapter<String>(this,
                                                                                            android.R.layout.simple_spinner_item, from);
            fromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            fromSpinner.setAdapter(fromAdapter);
            
            ArrayAdapter<String> toAdapter = new ArrayAdapter<String>(this,
                                                                                      android.R.layout.simple_spinner_item, to);
            toAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            toSpinner.setAdapter(toAdapter);
            
            
            users_spinner.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent,View view,int position,long id) {
                        MyData d = values[position];
                        selectedUser= d.getValue() ;
                    }

                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                }
            );
                                
          }
        /**
         * Set Date picket to current day
         * @author Rayan Zahab <differentruna@gmail.com> 
         */
        public void setCurrentDateOnView() {

            tvDisplayDate = (TextView) findViewById(R.id.tvDate);

            final Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH);
            day = c.get(Calendar.DAY_OF_MONTH);
            try 
            {
                    selectedDate = ourFormat.parse(tvDisplayDate.getText().toString());
            } 
            catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            }
            // set current date into textview
            tvDisplayDate.setText(new StringBuilder().append(month + 1).append("/").append(day).append("/").append(year));
        }
        /**
         * Add listeners to buttons: changeDate, Reserve button
         * @author Rayan Zahab <differentruna@gmail.com> 
         */
        public void addListenerOnButton() {

	        btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
	        btnReserve = (Button) findViewById(R.id.btnAddReservation);
	        
	        btnReserve.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    try 
                    {
                            selectedDate = ourFormat.parse(tvDisplayDate.getText().toString());
                    } 
                    catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }

                    Spinner toSpinnerValue = (Spinner) findViewById(R.id.toSpinner);
                    Spinner fromSpinnerValue = (Spinner) findViewById(R.id.fromSpinner);
                    String from = fromSpinnerValue.getSelectedItem().toString();
                    String to = toSpinnerValue.getSelectedItem().toString();
                    //Validate the chose Day, from and to are available for the selected ROOM
                    if(validate(selectedDate, Integer.parseInt(from), Integer.parseInt(to))){
                            //If the chosen time is available reserve the room
                            reserve(roomId,  Integer.parseInt(selectedUser),  selectedDate,  from, to);    
                            
                    }                               
                }                       

            });
            //SHow the date picket 
            btnChangeDate.setOnClickListener(new OnClickListener() {

                    @SuppressWarnings("deprecation")
                    @Override
                    public void onClick(View v) {
                            showDialog(DATE_DIALOG_ID);
                    }

            });

        }

        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DATE_DIALOG_ID:
                    // set date picker as current date
                    return new DatePickerDialog(this, datePickerListener, year, month,day);
            }
            return null;
        }
        
        /**
         * Reserve the passed @roomId for the user_id on day @Date from @from to @to
         * @author Rayan Zahab <differentruna@gmail.com> 
         */
    private void reserve(int roomId, int user_id, Date date, String from, String to)
    {
        try
        {                            
            Reservation res=new Reservation();
            res.setDate(date);
            res.setFrom(from);
            res.setTo(to);
            res.setRoomId(roomId);
            res.setUserId(user_id);
            db.insertRow(res);                      
            //Display all Reservations     
            Intent is = new Intent(getApplicationContext(), ReservationsFilterListActivity.class);			
			String[] res_ids = displayReservations("0","0",date);

	        is.putExtra("selected", res_ids);
	        startActivity(is);
        }
        catch (Exception e)
        {
            Log.e("Update Error", e.toString());
            e.printStackTrace();
        }
    }
    /**
     * Validates the chosen date and time for the selected room
     * @author Rayan Zahab <differentruna@gmail.com> 
     */
    private boolean validate(Date d, int from, int to){
	    ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
	    //get reservation of the selected date
	    dataArrays=db.getRowAsArrayByPosition(1,"Reservation",d.toString());
	    TextView error = (TextView) findViewById(R.id.error);
	    error.setText("");
	    int rId;
	    Boolean myReturn = true;
	    if(from>=to)
	    {
	            error.setText("From should be smaller than To");
	            return myReturn= false;
	    }
	    for (int position=0; position < dataArrays.size(); position++)
	    {
	            ArrayList<Object> row = dataArrays.get(position);
	            rId = Integer.parseInt(row.get(4).toString());
	            if(roomId==rId)
	            {                    
	                String f=row.get(2).toString();
	                String t=row.get(3).toString();
	                int roomfrom = Integer.parseInt(f);                     
	                int roomto = Integer.parseInt(t);
	                if( ( (roomfrom<=from) && (from<roomto) ) || (roomfrom == from) )
	                {
	                        error.setText("From is not valid!");
	                        myReturn= false;
	                }
	                else if( ( (roomfrom<to) && (to<=roomto) ) || (roomto ==to) )
	                {
	                        error.setText("To is not valid!");
	                        myReturn= false;
	                }
	            }
	    } 
        return myReturn;
    }       
        private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

            // when dialog box is closed, below method will be called.
            public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay) {
                year = selectedYear;
                month = selectedMonth;
                day = selectedDay;
                // set selected date into textview
                tvDisplayDate.setText(new StringBuilder().append(month + 1).append("/").append(day).append("/").append(year));
                try {
                        selectedDate = ourFormat.parse(tvDisplayDate.getText().toString());
                } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                    
            }
        };

        /**
    	 * Prints all reservations of a selected date for the selected room
    	 * @author Rayan Zahab <differentruna@gmail.com> 
    	 */	
    	private String[] displayReservations(String selectedRoom,String selectedUser,Date selectedDate)
    	{
    		ArrayList<String> res_ids = new ArrayList<String>();
        	
        	        
        	ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
        	dataArrays=db.getRowAsArrayByPosition(1,"Reservation",selectedDate.toString());
        	System.out.println("disp: "+dataArrays.size());
        	if(dataArrays.size()<1)
        	{
        		//reservations.setText("No reservations!");
        		System.out.println("no reser");
        	}
        	else
        	{
    	    	for (int position=0; position < dataArrays.size(); position++)
    	    	{	    		
    	    		ArrayList<Object> row = dataArrays.get(position);
    	    		 
    	    		String room=row.get(4).toString();
    	    		String user=row.get(5).toString();
    	    		
        			if( (!selectedRoom.equals("0")) && (selectedUser.equals("0")))
    	    		{	
    		    		if(room.equals(selectedRoom))
    		    		{
    		    			res_ids.add(row.get(0).toString());
    		    		}
    	    		}
    	    		else if( (selectedRoom.equals("0")) && (!selectedUser.equals("0")))
    	    		{	
    		    		if(user.equals(selectedUser))
    		    		{
    		    			res_ids.add(row.get(0).toString());
    		    		}
    	    		}
    	    		else if( (selectedRoom.equals("0")) && (selectedUser.equals("0")))
    	    		{
    	    			res_ids.add(row.get(0).toString());
    	    		}else if( (selectedRoom.equals("0")) && (selectedUser.equals("0")))
    	    		{
    	    			if( (user.equals(selectedUser)) && (room.equals(selectedRoom)) )
    		    		{
    		    			res_ids.add(row.get(0).toString());
    		    		}
    	    		}
    	    			
    	    	} 
        	}		
    		String[] return_ids = new String[res_ids.size()];
    		for(int i=0;i<res_ids.size();i++)
    		{
    			return_ids[i]=res_ids.get(i);
    		}
    		return return_ids;
    	}
        
        class MyData {
        public MyData( String spinnerText, String value ) {
            this.spinnerText = spinnerText;
            this.value = value;
        }

        public String getSpinnerText() {
            return spinnerText;
        }

        public String getValue() {
            return value;
        }

        public String toString() {
            return spinnerText;
        }

        String spinnerText;
        String value;
    }

    	/**
  	   * This function create the menu in the user info activity
  	   * @author Moustafa Chouraiki <mrsafu@gmail.com>
  	   * @param menu
  	   */
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.reservation_menu, menu);              
         return true;
     }
     
     /**
       * This function handles clicking any of the menu's items
       * @author Rayan Zahab <differentruna@gmail.com> 
       * @author Hyame Alameddine <hyame.alameddine@gmail.com>
       * @param menu
       */
     @Override
     public boolean onOptionsItemSelected(MenuItem item) 
      {       
          Intent i;
          
          switch (item.getItemId()) 
          {
           
          case R.id.users:     
                i = new Intent(getApplicationContext(), UsersListActivity.class);
                startActivity(i);
                break;
          case R.id.conferences:     
                i = new Intent(getApplicationContext(), RoomsListActivity.class);
                startActivity(i);
                break;
          case R.id.edit_profile:                         
                i = new Intent(getApplicationContext(), RegisterActivity.class);
                i.putExtra("editAdmin", 1);
                startActivity(i);
                break;
          case R.id.logout: 
                i = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(i);
                break;
          case R.id.help:     
                AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setTitle("Help!");
                alertDialog.setMessage("Gestion de conference is an application helps you manage reservations, add rooms ,add users and reserve rooms to organize conferences !");
                alertDialog.setIcon(R.drawable.icon);
                alertDialog.show();
                break;
          case R.id.developers: 
                Toast.makeText(this, "Rayan,Hyame,Mostafa!", Toast.LENGTH_LONG).show();
                break;
            
        }
        return true;
    }   
        
        
}